const axios = require('axios');

// API基础地址
const BASE_URL = 'http://localhost:3000/api';

// 测试账户信息
const TEST_ACCOUNTS = {
  admin: { phone: '13800138000', password: '123456' },
  maintainer: { phone: '13800138001', password: '123456' },
  user: { phone: '13800138002', password: '123456' }
};

// 存储认证token
let tokens = {};
let testOrderId = null;

// 测试API连接
const testConnection = async () => {
  try {
    console.log('🔗 测试API连接...');
    const response = await axios.get(`${BASE_URL.replace('/api', '')}/health`, { timeout: 5000 });
    if (response.data.success) {
      console.log('✅ API服务连接正常');
      console.log('📊 服务版本:', response.data.data.version);
      return true;
    }
  } catch (error) {
    console.error('❌ API服务连接失败:', error.message);
    if (error.code === 'ECONNREFUSED') {
      console.error('🔧 请确保服务器已启动: npm run dev');
    }
    return false;
  }
};

// 测试用户登录
const testLogin = async (role) => {
  try {
    console.log(`🔐 测试${role}登录...`);
    const account = TEST_ACCOUNTS[role];
    
    const response = await axios.post(`${BASE_URL}/auth/login`, account, { timeout: 10000 });
    
    if (response.data.success) {
      tokens[role] = response.data.data.token;
      console.log(`✅ ${role}登录成功`);
      console.log(`   用户: ${response.data.data.user.name}`);
      console.log(`   角色: ${response.data.data.user.role}`);
      console.log(`   ID: ${response.data.data.user.id}`);
      return response.data.data.user;
    }
  } catch (error) {
    console.error(`❌ ${role}登录失败:`, error.response?.data?.message || error.message);
    if (error.response?.status === 401) {
      console.error('🔧 建议运行: npm run init 初始化测试账户');
    }
    return null;
  }
};

// 测试创建工单
const testCreateOrder = async () => {
  try {
    console.log('📝 测试创建工单...');
    
    const orderData = {
      title: '测试工单-空调维修',
      description: '客厅空调不制冷，需要检查压缩机和制冷剂。问题出现已经3天，影响正常使用。',
      type: 'repair',
      urgency: 'high',
      userAddress: '北京市朝阳区测试小区1号楼101室',
      images: [],
      documents: []
    };

    const response = await axios.post(`${BASE_URL}/orders`, orderData, {
      headers: { Authorization: `Bearer ${tokens.user}` },
      timeout: 10000
    });

    if (response.data.success) {
      testOrderId = response.data.data._id;
      console.log('✅ 工单创建成功');
      console.log(`   工单号: ${response.data.data.orderNumber}`);
      console.log(`   状态: ${response.data.data.status}`);
      console.log(`   ID: ${testOrderId}`);
      return testOrderId;
    }
  } catch (error) {
    console.error('❌ 工单创建失败:', error.response?.data?.message || error.message);
    return null;
  }
};

// 测试获取工单列表
const testGetOrders = async (role) => {
  try {
    console.log(`📋 测试${role}获取工单列表...`);
    
    const response = await axios.get(`${BASE_URL}/orders?pageSize=5`, {
      headers: { Authorization: `Bearer ${tokens[role]}` },
      timeout: 10000
    });

    if (response.data.success) {
      const orders = response.data.data.data;
      const pagination = response.data.data.pagination;
      console.log(`✅ 工单列表获取成功`);
      console.log(`   当前页: ${pagination.page}/${pagination.totalPages}`);
      console.log(`   工单数: ${orders.length}/${pagination.total}`);
      
      if (orders.length > 0) {
        console.log(`   最新工单: ${orders[0].title} (${orders[0].status})`);
      }
      
      return true;
    }
  } catch (error) {
    console.error(`❌ ${role}获取工单列表失败:`, error.response?.data?.message || error.message);
    return false;
  }
};

// 测试获取维修员列表
const testGetMaintainers = async () => {
  try {
    console.log('🔧 测试获取维修员列表...');
    
    const response = await axios.get(`${BASE_URL}/users/maintainers/list`, {
      headers: { Authorization: `Bearer ${tokens.admin}` },
      timeout: 10000
    });

    if (response.data.success) {
      const maintainers = response.data.data;
      console.log(`✅ 维修员列表获取成功 (共${maintainers.length}位)`);
      
      if (maintainers.length > 0) {
        const maintainer = maintainers[0];
        console.log(`   维修员: ${maintainer.name} (评分: ${maintainer.rating})`);
        return maintainer._id;
      }
    }
  } catch (error) {
    console.error('❌ 获取维修员列表失败:', error.response?.data?.message || error.message);
    return null;
  }
};

// 测试派发工单
const testAssignOrder = async (orderId, maintainerId) => {
  try {
    console.log('🔄 测试派发工单...');
    
    const response = await axios.put(`${BASE_URL}/orders/${orderId}/assign`, {
      maintainerId,
      notes: '派发给李师傅处理，请尽快联系客户'
    }, {
      headers: { Authorization: `Bearer ${tokens.admin}` },
      timeout: 10000
    });

    if (response.data.success) {
      console.log('✅ 工单派发成功');
      console.log(`   维修员: ${response.data.data.maintainerName}`);
      console.log(`   状态: ${response.data.data.status}`);
      return true;
    }
  } catch (error) {
    console.error('❌ 工单派发失败:', error.response?.data?.message || error.message);
    return false;
  }
};

// 测试统计数据
const testStatistics = async () => {
  try {
    console.log('📊 测试统计数据...');
    
    const response = await axios.get(`${BASE_URL}/statistics`, {
      headers: { Authorization: `Bearer ${tokens.admin}` },
      timeout: 10000
    });

    if (response.data.success) {
      const stats = response.data.data;
      console.log('✅ 统计数据获取成功');
      console.log(`   总工单数: ${stats.totalOrders}`);
      console.log(`   待处理: ${stats.pendingOrders}`);
      console.log(`   进行中: ${stats.processingOrders}`);
      console.log(`   已完成: ${stats.completedOrders}`);
      console.log(`   完成率: ${stats.completionRate}%`);
      if (stats.averageRating > 0) {
        console.log(`   平均评分: ${stats.averageRating}`);
      }
      return true;
    }
  } catch (error) {
    console.error('❌ 统计数据获取失败:', error.response?.data?.message || error.message);
    return false;
  }
};

// 测试用户信息
const testUserProfile = async (role) => {
  try {
    console.log(`👤 测试${role}用户信息...`);
    
    const response = await axios.get(`${BASE_URL}/auth/me`, {
      headers: { Authorization: `Bearer ${tokens[role]}` },
      timeout: 10000
    });

    if (response.data.success) {
      const user = response.data.data;
      console.log(`✅ ${role}用户信息获取成功`);
      console.log(`   姓名: ${user.name}`);
      console.log(`   手机: ${user.phone}`);
      console.log(`   角色: ${user.role}`);
      if (user.role === 'maintainer') {
        console.log(`   评分: ${user.rating} | 完成工单: ${user.completedOrders}`);
      }
      return true;
    }
  } catch (error) {
    console.error(`❌ ${role}用户信息获取失败:`, error.response?.data?.message || error.message);
    return false;
  }
};

// 运行完整测试
const runFullTest = async () => {
  console.log('🚀 开始HarmonyOS工单管理系统API测试...\n');

  // 1. 测试连接
  const connectionOk = await testConnection();
  if (!connectionOk) {
    console.log('\n❌ 无法连接到API服务，测试终止');
    return false;
  }

  console.log('');

  // 2. 测试登录
  console.log('🔐 用户认证测试');
  console.log('='.repeat(40));
  
  const users = {};
  for (const role of ['admin', 'maintainer', 'user']) {
    users[role] = await testLogin(role);
    if (!users[role]) {
      console.log('\n❌ 用户认证失败，请运行 npm run init 初始化数据库');
      return false;
    }
  }

  console.log('\n📋 工单管理测试');
  console.log('='.repeat(40));

  // 3. 测试工单功能
  const orderId = await testCreateOrder();
  if (!orderId) {
    console.log('❌ 工单创建失败，跳过后续工单测试');
  } else {
    console.log('');
    await testGetOrders('user');
    await testGetOrders('admin');
    
    // 4. 测试派发功能
    console.log('');
    const maintainerId = await testGetMaintainers();
    if (maintainerId) {
      await testAssignOrder(orderId, maintainerId);
    }
  }

  console.log('\n👤 用户管理测试');
  console.log('='.repeat(40));

  // 5. 测试用户信息
  for (const role of ['admin', 'maintainer', 'user']) {
    await testUserProfile(role);
  }

  console.log('\n📊 统计数据测试');
  console.log('='.repeat(40));

  // 6. 测试统计功能
  await testStatistics();

  console.log('\n🎉 API测试完成！');
  console.log('='.repeat(50));
  console.log('✅ 数据库连接正常');
  console.log('✅ 用户认证功能正常');
  console.log('✅ 工单管理功能正常');
  console.log('✅ 用户管理功能正常');
  console.log('✅ 统计数据功能正常');
  console.log('\n🌟 HarmonyOS工单管理系统后端已准备就绪！');
  console.log('🔗 您现在可以连接HarmonyOS前端应用进行测试');
  
  return true;
};

// 如果直接运行此文件，执行测试
if (require.main === module) {
  runFullTest().catch(error => {
    console.error('\n❌ 测试过程中出现错误:', error.message);
    console.error('🔍 请检查服务器是否正常运行');
    process.exit(1);
  });
}

module.exports = {
  testConnection,
  testLogin,
  testCreateOrder,
  testGetOrders,
  testAssignOrder,
  testStatistics,
  testUserProfile,
  runFullTest
};